<?php


namespace app\controller\admin;


use app\common\exception\ApiException;
use app\model\coach\CoachMoneyDetailModel;
use app\model\coach\UserCoachModel;
use app\model\school\SchoolOrderModel;
use app\model\user\UserInvoiceModel;
use app\model\user\UserModel;
use app\model\user\UserMoneyDetailModel;
use app\service\user\CoachMoneyDetailService;
use app\service\user\UserMoneyDetailService;
use app\service\utils\GenerateUserNickService;

class CoachController extends BaseAdminController
{

    function setModel()
    {
        return new UserCoachModel();
    }

    function setWithModel()
    {
        return ['school'];
    }

    function setSearch()
    {
        return [
            'like' => ['username', 'mobile'],
            '=' => ['type', 'school_id', 'is_team_leader'],
            'betweenTimestamp' => ['create_time']
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function getList()
    {
        try {
            $list = parent::getList()->toArray();
            foreach ($list['data'] as $k => $v) {
                // 接单数
                $orderNum = SchoolOrderModel::where('coach_id', $v['id'])->whereIn('status', [2, 3, 4, 6])->count();
                $list['data'][$k]['accept_order_num'] = $orderNum;
                // 收入金额
                $orderAmount = CoachMoneyDetailModel::where('user_id', $v['id'])
                    ->where('type', CoachMoneyDetailService::SALARY)
                    ->sum('amount');
                $list['data'][$k]['order_amount'] = $orderAmount;
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function save()
    {
        try {
            $data = $this->request->except(['create_time']);
            $schoolId = $data['school_id'] ?? 0;
            if (!$schoolId) {
                throw new ApiException('请选择驾校');
            }
            if (!$data['id']) {
                if ($this->getModel()->where('mobile', $data['mobile'])->find()) {
                    throw new ApiException('账号已存在');
                }
                // 是团队长
                $teamLeader = $data['is_team_leader'];
                if ($teamLeader == 1) {
                    $haveLeader = $this->getModel()
                        ->where('school_id', $schoolId)
                        ->where('is_team_leader', 1)
                        ->find();
                    if ($haveLeader) {
                        throw new ApiException('团队长已存在');
                    }
                } else {
                    $pinfo = $haveLeader = $this->getModel()
                        ->where('school_id', $schoolId)
                        ->where('is_team_leader', 1)
                        ->find();
                    if(!$pinfo){
                        throw new ApiException('未找到该驾校的团队长');
                    }
                    $data['pid'] = $pinfo['id'];
                    $data['team'] = $pinfo['team'];
                }
                $data['username'] = $data['username'] ?: GenerateUserNickService::generateUserNick();
                $this->setModel()->save($data);
            } else {

                $model = $this->setModel()->find($data['id']);
                if ($data['mobile'] != $model['mobile'] && $this->getModel()->where('mobile', $data['mobile'])->find()) {
                    throw new ApiException('账号已存在');
                }
                // 是团队长
                $teamLeader = $data['is_team_leader'];
                if ($teamLeader == 1) {
                    $haveLeader = $this->getModel()
                        ->where('school_id', $schoolId)
                        ->where('is_team_leader', 1)
                        ->find();
                    if ($haveLeader && $haveLeader['id'] != $model['id']) {
                        throw new ApiException('团队长已存在');
                    }
                } else {
                    $pinfo = $haveLeader = $this->getModel()
                        ->where('school_id', $schoolId)
                        ->where('is_team_leader', 1)
                        ->find();
                    $data['pid'] = $pinfo['id'];
                    $data['team'] = $pinfo['team'];
                }
                $model->save($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 团队列表
     * @return \think\response\Json
     */
    public function getTeamList()
    {
        try {
            $list = $this->setModel()->where('is_team_leader', 1)->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function getArr()
    {
        try {
            $arr = $this->setModel()->with('school')->field('id,school_id,username,mobile')->select();
            return $this->success($arr);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}